﻿using System;
using System.Collections.Generic;
using System.Text;
using DecodeInterface;
using System.Drawing;

namespace MotionDetect
{
    public class EliminateShake : DecodeBitmap
    {
        int ticks = 0;
        Point[] pointFeatures;
        byte[] mouldFeature;
        Point[] pointParticles;
        Rectangle rectFeature;
        Size offSet = new Size();
        protected override unsafe object[] OnDecode(byte* pIn, byte* pOut, Size sizeIn, Size sizeOut, params object[] state)
        {
            if (ticks++ % 100 == 0)
            {
                //特征区域
                rectFeature = new Rectangle(0, 0, sizeIn.Width, sizeIn.Height);
                rectFeature.Inflate(-50, -50);
                rectFeature.Offset(-50, -50);
                //提取全局随机正态分布特征点
                pointFeatures = DataManager.GetRandomPoint(rectFeature, 10000);
                //提取全局特征直方图
                rectFeature.Offset(50, 50);
                mouldFeature = DataManager.GetFeatureHistogram(rectFeature, pIn, sizeIn, pointFeatures);
                offSet = new Size();
            }
            else if (pointFeatures != null && mouldFeature != null)
            {
                Point pointMaxFeature = rectFeature.Location;
                //获取原始区域特征值
                byte[] particleMaxFeature = DataManager.GetFeatureHistogram(rectFeature, pIn, sizeIn, pointFeatures);
                //获取原始区域与模板的相似度
                double maxFeature = DataManager.GetSimilarFeature(mouldFeature, particleMaxFeature);

                //获取粒子
                pointParticles = DataManager.GetRandomPoint(new Rectangle(0, 0, 100, 100), 100);
                foreach (var particle in pointParticles)
                {
                    //获取粒子特征
                    byte[] particleFeature = DataManager.GetFeatureHistogram(
                        new Rectangle(particle, rectFeature.Size), pIn, sizeIn, pointFeatures);
                    //获取粒子特征与模板特征的相似度
                    double feature = DataManager.GetSimilarFeature(mouldFeature, particleFeature);
                    if (feature > maxFeature)
                    {
                        maxFeature = feature;
                        pointMaxFeature = particle;
                        particleMaxFeature = particleFeature;
                    }
                }
                pointMaxFeature.Offset(-50,-50);
                offSet = new Size(pointMaxFeature.X, pointMaxFeature.Y);
            }

            DataManager.OffSetImage(pIn, pOut, sizeIn, sizeOut, offSet.Width, offSet.Height);

            return new object[0];
        }
    }
}
